import config from '../config';
import mathTool from '../../../common/mathTool';

import passwordDialog from '../passwordDialog.html';
import confirm from "../../confirm/confirm";

const STATUS_NOT_OPEN = 'INIT';
const STATUS_HAS_OPEN = 'LISTED';
const STATUS_CLOSED = 'DELISTED';

class ListController {
    constructor($scope, settingsSvc, tradeControlSvc, $uibModal, $location, $cookies) {
        "ngInject";

        this.$scope = $scope;
        this.service = settingsSvc;
        this.$uibModal = $uibModal;
        this.$location = $location;
        this.$cookies = $cookies;

        // 用于交易开关
        this.tradeControlSvc = tradeControlSvc;

        this.config = config;


        // ================================ 交易手续费
        this.isListLoading = true;

        // ================================ 交易开关 和 手续费列表写在一个list里面了
        this.list = [];


        this.STATUS_NOT_OPEN = STATUS_NOT_OPEN;
        this.STATUS_HAS_OPEN = STATUS_HAS_OPEN;
        this.STATUS_CLOSED = STATUS_CLOSED;


        // console.log(this.$scope.$root.$coinList);

        this.init();
    }

    init() {
        this._fetchTotalList();
    }

    // 根据symbol获取展示的类型
    _getSymbolView(symbol) {
        return symbol.split('_').reverse().join('/');
    }

    // ================================================================================================================================================ 交易对 开关 费率 获取列表 刷新
    _fetchTotalList() {
        let that = this;

        this.isListLoading = true;

        $.when( this._fetchSymbolList(), this.tradeControlSvc.profileList() ).done((symbolListRep, configListRep) => {
            this.isListLoading = false;

            // console.log('交易对开关',repSwitch.data.slice(0,5));
            // console.log('费率',feeRep.data.slice(0,5));

            let symbolList = [];

            // 交易对初始化列表
            if (symbolListRep.code === window.CODE.SUCCESS) {
                symbolList = getSymbolMap(symbolListRep.data);
            } else {
                window.toast(symbolListRep.msg);
            }

            // 交易对配置列表
            if (configListRep.code === window.CODE.SUCCESS) {
                symbolList = getConfigMap(configListRep.data, symbolList);
                that.list = symbolList;
            } else {
                window.toast(configListRep.msg);
            }

            /**
             * 将交易对的初始化信息融到symbolList
             * @param list
             * @returns {Array}
             */
            function getSymbolMap(list) {
                let resArr = [];
                let coinList = that.$scope.$root.$symbolList;

                // 根据全局 coinSymbolList  将相应的币种放入数组中
                for (let i = 0; i < coinList.length; i++) {
                    for (let j = 0; j < list.length; j++) {
                        if (coinList[i].value === list[j].symbol) {
                            resArr.push(list[j]);
                        }
                    }
                }
                return resArr;
            }

            /**
             * 将两个列表，即配置列表融到symbolList中
             * @param configList
             * @param symbolList
             */
            function getConfigMap(configList, symbolList) {
                $.map(configList, (item, index) => {
                    // item.profileValue = mathTool.multiplication(item.profileValue, 100) || 0;

                    for (let i = 0; i < symbolList.length; i++) {
                        if (item.symbol === symbolList[i].symbol) {

                            // 判断配置项
                            if (item.profileKey === config.ASSETFEERATE) {    // 1.网络确认数
                                symbolList[i][config.ASSETFEERATE] = mathTool.multiplication(item.profileValue, 100) || 0;
                                symbolList[i][config.ASSETFEERATE + '_INPUT'] = '';
                            } else {
                                symbolList[i][item.profileKey] = item.profileValue;
                                symbolList[i][item.profileKey + '_INPUT'] = '';
                            }

                            // if (item.profileKey === config.PRICEPRECISION) {    // 1.网络确认数
                            //     symbolList[i][config.PRICEPRECISION] = item.profileValue;
                            //     symbolList[i][config.PRICEPRECISION + '_INPUT'] = '';
                            // }
                            //
                            // if (item.profileKey === config.AMOUNTPRECISION) {    // 1.网络确认数
                            //     symbolList[i][config.AMOUNTPRECISION] = item.profileValue;
                            //     symbolList[i][config.AMOUNTPRECISION + '_INPUT'] = '';
                            // }
                            //
                            // if (item.profileKey === config.HIGHLIGHTNO) {    // 1.网络确认数
                            //     symbolList[i][config.HIGHLIGHTNO] = item.profileValue;
                            //     symbolList[i][config.HIGHLIGHTNO + '_INPUT'] = '';
                            // }



                            // symbolList[i].transactionFeeInputValue = '';
                            // symbolList[i].pricePrecisionInputValue = '';
                            // symbolList[i].amountPrecisionInputValue = '';
                            // symbolList[i].highlightNoInputValue = '';
                        }
                    }
                });
                return symbolList;
            }

        });
    }

    _fetchSymbolList() {
        return this.tradeControlSvc.list({
            pageNo: 0,
            pageSize: 500
        });
    }

    update(symbol, key, value) {
        let that = this;

        if ($.trim(value) === '') {
            window.toast(`输入不可为空！`);
            return;
        }
        let api = key == 'rank' ? 'updateUp' : 'update'

        confirm('确认要进行该操作吗？', () => {

            let modalInstance = this.$uibModal.open({
                template: passwordDialog,
                scope: this.$scope,
                controller() {
                }
            });

            this.$scope.$$ok = function (password) {
                window.toast('请稍候...');
                that.tradeControlSvc[api]({
                    configSymbol: symbol,
                    key: key,
                    value: value
                }, {
                    'login-password': password
                }).then(rep => {
                    if(rep.code === window.CODE.SUCCESS){
                        window.toast('操作成功', {
                            callback() {
                                that._fetchTotalList();
                            }
                        });
                    }else{
                        window.toast(rep.msg);
                    }
                });
                modalInstance.dismiss('ok');
            };

            this.$scope.$$cancel = function () {
                modalInstance.dismiss('cancel');
            };

        });
    }

    updateShow(symbol, key, value) {
        let that = this;

        let operText;
        if (value === 'ON') {
            operText = '展示';
        } else {
            operText = '隐藏';
        }

        confirm('确定要' + operText + '交易对' + symbol + '吗?', () => {

            let modalInstance = this.$uibModal.open({
                template: passwordDialog,
                scope: this.$scope,
                controller() {
                }
            });

            this.$scope.$$ok = function (password) {
                window.toast('请稍候...');
                that.tradeControlSvc.update({
                    configSymbol: symbol,
                    key: key,
                    value: value
                }, {
                    'login-password': password
                }).then(rep => {
                    if(rep.code === window.CODE.SUCCESS){
                        window.toast('操作成功', {
                            callback() {
                                that._fetchTotalList();
                            }
                        });
                    }else{
                        window.toast(rep.msg);
                    }
                });
                modalInstance.dismiss('ok');
            };

            this.$scope.$$cancel = function () {
                modalInstance.dismiss('cancel');
            };

        });
    }

    /**
     * 更新交易对开关状态
     */
    updateStatus(item, status, operText) {
        let that = this;
        let form = {
            symbol: item.symbol,
            assetCode1: item.assetCode1,
            assetCode2: item.assetCode2,
            title: item.title,
            name: item.name,
            description: item.description,
            minPrecision1: item.minPrecision1,
            minPrecision2: item.minPrecision2,
            minAmount1: item.minAmount1,
            minAmount2: item.minAmount2,
            maxAmount1: item.maxAmount1,
            maxAmount2: item.maxAmount2,
            status: status,
            pricePrecision: item.pricePrecision,
            amountPrecision: item.amountPrecision,
            highlightNo: item.highlightNo
        };

        confirm('确定要' + operText + '交易对' + form.symbol + '吗?', () => {
            that._updateAjax(that, form);
        });
    }

    _updateAjax(that, form) {
        let modalInstance = this.$uibModal.open({
            template: passwordDialog,
            scope: this.$scope,
            controller() {
            }
        });

        this.$scope.$$ok = function (password) {
            window.toast('请稍候...');
            that.isListLoading = true;


            that.tradeControlSvc.updateConfigSymbol(form, {
                'login-password': password
            }).then(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    window.toast('操作成功', {
                        callback() {
                            that._fetchTotalList();
                        }
                    });
                } else {
                    that.isListLoading = false;
                    window.toast(rep.msg);
                }
            });


            modalInstance.dismiss('ok');
        };

        this.$scope.$$cancel = function () {
            modalInstance.dismiss('cancel');
        };
    }


    // =================================================================================================================================== 交易手续费
    _updateOneTransactionFee(symbol, value) {
        this.list.some((item, index) => {
            if (item.symbol === symbol) {
                item.profileValue = value;
                item.transactionFeeInputValue = '';
                return true;
            }
        })
    }

    /**
     * 查询交易手续费
     */
    queryTransactionFee() {
        let that = this;
        let param = {
            key: config.TRANSACTION_KEY
        };
        return this.service.transactionQuery(param);
    }

    /**
     * 更新交易手续费
     * @param symbol
     * @param value
     */
    updateTransactionFee(symbol, value) {
        let that = this;

        if ($.trim(value) === '') {
            window.toast(`请输入${this._getSymbolView(symbol)}的交易手续费！`);
            return;
        }

        let modalInstance = this.$uibModal.open({
            template: passwordDialog,
            scope: this.$scope,
            controller() {
            }
        });

        this.$scope.$$ok = function (password) {
            if (value === '') {
                window.toast('请输入当前账号密码');
                return;
            }
            let param = {
                key: config.ASSETFEERATE,
                configSymbol: symbol,
                value: mathTool.division(value, 100)
            };
            window.toast('请稍候...');
            that.service.transactionUpdate(param, {
                'login-password': password
            }).then(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    window.toast(rep.msg);
                    that.init();

                    // that._updateOneTransactionFee(symbol,value);
                } else {
                    window.toast(rep.msg);
                }
            });
            modalInstance.dismiss('ok');
        };

        this.$scope.$$cancel = function () {
            modalInstance.dismiss('cancel');
        };
    }

}


export default ListController;
